package com.gzc.service.imp;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.gzc.common.Pager;
import com.gzc.common.exception.DocumentException;
import com.gzc.dao.IDepartmentDao;
import com.gzc.dao.IUserDao;
import com.gzc.model.Department;
import com.gzc.model.User;
import com.gzc.service.IUserService;

@Service("userService")
public class UserService implements IUserService {
	
	private IUserDao userDao;
	private IDepartmentDao departmentDao;
	
	@Resource
	public void setDepartmentDao(IDepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}
	@Resource
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void add(User u, int depId) {
		if(null != this.loadByUsername(u.getUsername())){
			throw new DocumentException("要添加的用户已经存在不能添加！");
		}
		Department dep = departmentDao.load(depId);
		u.setDepartment(dep);
		userDao.add(u);
	}

	@Override
	public void del(int userId) {
		// TODO 加入删除关联对象的代码，需要关联删除文档、消息对象。
		userDao.delete(userId);
	}

	@Override
	public void update(User u, int depId) {
		Department dep = departmentDao.load(depId);
		u.setDepartment(dep);
		userDao.update(u);		
	}
	
	@Override
	public void update(User u) {		
		userDao.update(u);		
	}

	@Override
	public User load(int userId) {
		return userDao.load(userId);
	}

	@Override
	public Pager<User> findUserByDep(Integer depId) {
		Pager<User> users = null;
		if(null == depId || depId < 1){
			users = userDao.find("from User");
		}else{
			users = userDao.find("from User where department.id =?", depId);
		}
		return users;
	}
	
	private User loadByUsername(String username){
		String hql = "select u from User u where u.username=?";
		return (User)this.userDao.queryByHql(hql, username);
	}
	@Override
	public User login(String username, String password) {
		User u = loadByUsername(username);
		if(null == u){
			throw new DocumentException("用户名不存在！");
		}
		if(!u.getPassword().equals(password)){
			throw new DocumentException("密码不正确！");
		}
		return u;
	}
	
	/**
	 * 根据用户id获取能够发送私人信息的所有用户
	 * @param userId
	 * @return
	 */
	@Override
	public List<User> listAllSendUser(int userId){
		return userDao.listAllCanSendUser(userId);
	}

}
